# -*- coding: utf-8 -*-

import uvicorn
from fastapi import FastAPI,Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from backend.app.config import settings
from backend.app.api import chat_routes, session_routes
from fastapi.staticfiles import StaticFiles
import sys
import os
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).parent
sys.path.append(str(project_root))

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description="AI聊天助手API，支持多Agent管理、文档处理和智能聊天",
    version=settings.APP_VERSION,
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载API路由
app.include_router(chat_routes.router, prefix=settings.API_PREFIX)
app.include_router(session_routes.router, prefix=settings.API_PREFIX)

# 挂载前端静态文件
# app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="static")

# 自定义静态文件服务
@app.get("/{path:path}")
async def serve_static(request: Request, path: str):
    # 处理根路径
    if path == "":
        path = "index.html"
    
    # 构建完整文件路径
    static_path = Path("frontend/dist") / path
    
    # 检查文件是否存在
    if not static_path.exists():
        # 如果请求的是API路径，返回404
        if path.startswith("api/"):
            return {"error": "Not found"}, 404
        
        # 否则返回前端应用的入口文件
        static_path = Path("frontend/dist/index.html")
    
    # 返回文件响应
    return FileResponse(static_path)

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        workers=1
    )    